import { app } from "electron";
import path from "path";
import fs from "fs/promises";
import { AppConfig, DEFAULT_CONFIG } from "./types";

const configPath = path.join(app.getPath("userData"), "config.json");
let config: AppConfig = { ...DEFAULT_CONFIG };

export const configManager = {
  async load() {
    try {
      const raw = await fs.readFile(configPath, "utf-8");
      config = { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
    } catch (error) {
      await this.save();
    }
    return config;
  },
  async save() {
    await fs.writeFile(configPath, JSON.stringify(config, null, 2));
    return config;
  },
  get() {
    return config;
  },
  async update(updates: Partial<AppConfig>) {
    config = { ...config, ...updates };
    await this.save();
    return config;
  }
};
